from django.http import HttpResponse
from django.core.cache import cache

from ...models.configs import Configs

from ...utils.sms import send_code_email, SendCodePhone

import json
import random

def send_code(request):
    '''
    发送验证码
    POST
    re = {
        "receiver": "18201419965@163.com",
        "key": "",
        "dots": null
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 生成6位数验证码
        random_num = random.randint(100000, 999999)
        # print(random_num)

        receiver_str = json_obj['receiver']

        system_config_register_list = Configs.objects.get(marker="system").config_json['register_ways']
        # 判断是手机号还是邮箱
        if "@" in receiver_str:
            # 邮箱
            if "email" in system_config_register_list:
                send_res = send_code_email(receiver_str, random_num)
            else:
                res_mes = {
                    "code": 1,
                    "message": "系统已禁用邮箱注册！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            # 手机号
            if "mobile" in system_config_register_list:
                mes_list = [receiver_str, random_num]
                send_res = SendCodePhone.main(mes_list)
            else:
                res_mes = {
                    "code": 1,
                    "message": "系统已禁用手机号注册！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)

        # 判断是否发送成功验证码
        if not send_res:
            res_mes = {
                "code": 1,
                "data": "验证码发送失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        # 存储验证码，等待后面注册验证
        code_store_prefix = "/verify/codes/{}".format(receiver_str)
        try:
            cache.set(code_store_prefix, random_num, timeout=300)
        except:
            res_mes = {
                "code": 1,
                "data": "验证码保存失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

